package com.fuhe.chen.vendingmachine.security;

import com.fuhe.chen.vendingmachine.pojo.User;
import com.fuhe.chen.vendingmachine.service.IUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Set;

/**
 * 登录验证
 * 包括账号验证 和 权限验证
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    IUserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //TODO:后期增加权限认证
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        if(!principalCollection.isEmpty()) {
            Set<String> realmNames = principalCollection.getRealmNames();
            for (String realmName : realmNames) {
                if (realmName.equals("admin")){
                    info.addStringPermission("admin");
                    info.addRole("admin");
                }
                if (realmName.equals("supplier")){
                    info.addStringPermission("supplier");
                    info.addRole("supplier");
                }
            }
        }
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken token= (UsernamePasswordToken)authenticationToken;

        String username = token.getUsername();
        User user = userService.findOne(username);
        if(null == user){
            return null;
        }
        String password = user.getPassword();
        String role = user.getRole()==null?"":user.getRole();

        return new SimpleAuthenticationInfo(user,password,role);
    }
}
